package com.istock.sampleservice.feign;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.istock.base.logtrace.filter.TraceNoFilter;
import com.istock.base.logtrace.utils.TraceNoUtils;
import com.istock.base.web.utils.LocalRequestHolder;

import feign.RequestInterceptor;
import feign.RequestTemplate;

@Component
public class InheritHeaderInterceptor implements RequestInterceptor {

	private String[] headers;
	public String[] getHeaders() {
		return headers;
	}
	public void setHeaders(String[] headers) {
		this.headers = headers;
	}
	
	@Override
	public void apply(RequestTemplate template) {
        
		HttpServletRequest request = LocalRequestHolder.findRequest();
		if(request != null && headers != null) {
			for(String headName : headers) {
				String headValue = request.getHeader(headName);
				if(StringUtils.isNotBlank(headValue)) {
					template.header(headName, headValue);
				}
			}
		}
		
        String logTraceNo = TraceNoUtils.getTraceNo();
        if(StringUtils.isNotBlank(logTraceNo)) {
        	template.header(TraceNoFilter.LOGGER_HEADER, logTraceNo);
        }
	}

}
